package inet.app.vod.activity.common;

import inet.app.vod.activity.R;
import inet.app.vod.activity.film.IPhimActivity;
import inet.app.vod.config.AppConstants;
import inet.app.vod.db.DaoCategory;
import inet.app.vod.db.DaoFactory;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.CategoryModel;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyPreferenceManager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.inet.app.framework.bitmap.BitmapLargeManager;
import com.inet.app.framework.bitmap.BitmapLargeManager.LoadBitmapListener;
import com.inet.app.framework.device.DeviceInfoModel;
import com.inet.app.framework.device.DeviceUtil;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;

public class SplashActivity extends Activity {

	private int SPLASH_TIME = 2000;

	private ImageView mSplashImgView;
	private View mViewLoading;

	private boolean isActive = true;
	private int mSplashId = R.drawable.splash;
	private MyPreferenceManager mPref;

	Thread splashThread = new Thread() {

		@Override
		public void run() {
			try {
				int waitedTime = 0;
				while (isActive && (waitedTime < SPLASH_TIME)) {
					sleep(100);
					waitedTime = (isActive) ? waitedTime + 100 : waitedTime;
					isActive = (waitedTime == SPLASH_TIME) ? false : true;
				}
			} catch (InterruptedException e) {
				// do nothing
			} finally {
				// launch new activity
				Bundle bundle = new Bundle();
				bundle.putString("home_id", AppConstants.ID_IPHIM);
				LaunchIntent.start(SplashActivity.this, IPhimActivity.class,
						bundle);
				finish();
			}
		}
	};

	LoadBitmapListener mLoadBmpListener = new LoadBitmapListener() {

		@Override
		public void onLoadFinish(int resId, boolean isSuccess) {
			if (isSuccess) {
				Bitmap splashBmp = BitmapLargeManager.getInstance(
						SplashActivity.this).getBitmapFromCache(resId);
				mSplashImgView.setImageBitmap(splashBmp);
			} else {
				Log.e("load splash image failed");
			}
			mViewLoading.setVisibility(View.GONE);
			splashThread.start();
		}
	};

	private void initModels() {
		mPref = MyPreferenceManager.getInstance(getApplicationContext());

		// first setting
		LaunchIntent.isLaunchIntentWithAnimation = true;
		LaunchIntent.mEnterAnim = R.anim.fade_in;
		LaunchIntent.mExitAnim = R.anim.push_out;
		Log.DEFAULT_TAG = "VOD";

		DaoCategory daoCategory = DaoFactory.getInstance(
				getApplicationContext()).getDaoCategory();
		if (daoCategory.isExistData()) {
			return;
		}

		// insert 4 first menu iphim, iclip, inews, ifun
		// iPhim
		CategoryModel iPhim = new CategoryModel();
		iPhim.setId(AppConstants.ID_IPHIM);
		iPhim.setName(AppConstants.NAME_IPHIM);
		iPhim.setGroup(0);
		daoCategory.insertRow(iPhim);

		// iClip
		CategoryModel iClip = new CategoryModel();
		iPhim.setId(AppConstants.ID_ICLIP);
		iPhim.setName(AppConstants.NAME_ICLIP);
		iPhim.setGroup(0);
		daoCategory.insertRow(iClip);

		// iNews
		CategoryModel iNews = new CategoryModel();
		iPhim.setId(AppConstants.ID_INEWS);
		iPhim.setName(AppConstants.NAME_INEWS);
		iPhim.setGroup(0);
		daoCategory.insertRow(iNews);

		// iFun
		CategoryModel iFun = new CategoryModel();
		iPhim.setId(AppConstants.ID_IFUN);
		iPhim.setName(AppConstants.NAME_IFUN);
		iPhim.setGroup(0);
		daoCategory.insertRow(iFun);
		
	}

	private void initViews() {
		mViewLoading = findViewById(R.id.loading_layout);
		mSplashImgView = (ImageView) findViewById(R.id.splash_image);
		mSplashImgView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				isActive = false;
			}
		});

		// load splash (large bitmap) from asynctask
		final int resId = R.drawable.splash;
		DeviceInfoModel device = DeviceUtil.getSimpleDeviceInfo(this);
		BitmapLargeManager.getInstance(getApplicationContext()).loadLargeBimap(
				resId, device.getWidth(), device.getHeight(), mLoadBmpListener);

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		setContentView(R.layout.activity_splash);
		initModels();
		initViews();
		requestToken();
	}
	
	/**
	 * Request root token to add random user
	 */
	private void requestToken() {

		// clear old root token
		mPref.saveRootToken("");

		// request root token
		VolleyClient.requestRootToken(new VolleyListener(this) {

			@Override
			public void onSuccess(String response) {
				String token = Parse.parseToken(response);
				if (!TextUtils.isEmpty(token)) {
					Log.d("request root token success " + token);
					// add random user
					mPref.saveRootToken(token);
				} else {
					Log.e("request root token failed");
				}
			}

			@Override
			public void onStart() {
				Log.d("start request root token");
			}

			@Override
			public void onFinish() {
				Log.d("finish request root token");
			}

			@Override
			public void onError(VolleyError error) {
				Log.e("error request root token " + error.toString());
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (splashThread.isAlive()) {
			isActive = false;
			try {
				splashThread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {
		// remove large bitmap
		BitmapLargeManager.getInstance(getApplicationContext()).removeBitmap(
				mSplashId);
		super.onDestroy();
	}

}
